package com.example.presentshopping.ui.activity

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.webkit.WebSettings
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpActivity
import com.example.presentshopping.config.bean.DetailsBean
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL.Req_addGoodsStore
import com.example.presentshopping.net.http.HttpURL.Req_getDetail
import com.example.presentshopping.net.observer.TaskCallback
import com.example.presentshopping.ui.dialog.SukDialog
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.edit.StatusBarUtil
import com.example.presentshopping.utils.glide.GlideUtil
import com.example.presentshopping.utils.tool.GsonUtils
import com.example.presentshopping.utils.tool.IntentJumpUtils
import com.example.presentshopping.utils.tool.SoftHideKeyBoardUtil
import kotlinx.android.synthetic.main.activity_details.*
import org.jsoup.Jsoup
import org.jsoup.select.Elements


class DetailsActivity : BaseMvpActivity() {
    private var queryInfoPresenter: PublicPresenter? = null
    var id: String? = null
    var detailsBeaan: DetailsBean? = null
    private var serviceContent: String? = null
    var Miassactiviy: String? = null
    var store = true

    override val layoutId: Int
        get() = R.layout.activity_details

    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setRootViewFitsSystemWindows(this, false)
        SoftHideKeyBoardUtil.assistActivity(this)

        queryInfoPresenter = PublicPresenter(this, false, "")
        queryInfoPresenter?.attachView(this)
        id = intent.getStringExtra("msid")
        Miassactiviy = intent.getStringExtra("Activity")

        getGoosDetails(id)
        initWebView()

        Anorder.setOnClickListener {
            SukDialog(this@DetailsActivity, detailsBeaan, Miassactiviy).builder().show()
        }
        fl_back.setOnClickListener { finish() }

        shoucang_iv.setOnClickListener {
            if (IntentJumpUtils.isLogin()) {
                Setquery()
            } else {
                // 登录
                IntentJumpUtils.goToLogin(this@DetailsActivity, "")
            }

        }

    }

    override fun onDestroy() {
        queryInfoPresenter?.detachView()
        super.onDestroy()
    }


    fun getGoosDetails(id: String?) {
        queryInfoPresenter?.netWorkRequestPost(Req_getDetail, HttpRequest.getGoodsDetail(id))

    }

    override fun showToast(msg: String?) {
        ToastUtil.showMsg(msg)
    }

    @SuppressLint("SetTextI18n")
    override fun onSuccess(data: String?) {
        detailsBeaan = GsonUtils.getGson().fromJson(data, DetailsBean().javaClass)
        GlideUtil.load(context, detailsBeaan?.data?.thumb, iv_oil_station_image)
        title_tv.text = detailsBeaan?.data?.title
        marketprice.text = "¥: " + detailsBeaan?.data?.marketprice
        productprice.text = "原价 ¥: " + detailsBeaan?.data?.productprice
        productprice?.paint?.flags = Paint.STRIKE_THRU_TEXT_FLAG;
        totaltv.text = "库存：" + detailsBeaan?.data?.total
        salestv.text = "已售：" + detailsBeaan?.data?.sales.toString()
        Log.e("OrdermlyActivity", "------" + detailsBeaan?.data?.isteam)
        if (detailsBeaan?.data?.store == 1) {
            shoucang_iv.setImageResource(R.drawable.ic_shoucang1)
            store = true

        } else {
            shoucang_iv.setImageResource(R.drawable.ic_shoucang)
            store = false
        }


        if (detailsBeaan?.data?.isteam != 1) {
            Anorder.text = "立即购买"
        } else if(Miassactiviy?.contains("ProductListFragment")!!) {
            Anorder.text = "立即购买"
        }else{
            Anorder.text = "加入拼团"
        }
        detailsBeaan?.data?.detail?.let {
            getNewContent(it)?.let { it1 ->
                Log.e("DetailsActivity", it1)
                wv_service_content.loadDataWithBaseURL(
                    null,
                    it1, "text/html", "utf-8", null
                )
            }

        }

    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }

    /**
     * 初始化webview
     */
    private fun initWebView() {
        wv_service_content.setLayerType(View.LAYER_TYPE_NONE, null) //开启硬件加速
        val webSettings: WebSettings = wv_service_content.settings
        webSettings.javaScriptEnabled = true

        // User settings
        webSettings.javaScriptEnabled = true
        webSettings.javaScriptCanOpenWindowsAutomatically = true
        //关键点
        webSettings.useWideViewPort = true
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
        webSettings.displayZoomControls = false
        // 设置支持javascript脚本
        webSettings.javaScriptEnabled = true
        // 允许访问文件
        webSettings.allowFileAccess = true
        // 设置显示缩放按钮
        webSettings.builtInZoomControls = true
        // 支持缩放
        webSettings.setSupportZoom(true)
        webSettings.loadWithOverviewMode = true


        val metrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metrics)
        val mDensity = metrics.densityDpi
        if (mDensity == 240 || mDensity == 480) {
            webSettings.defaultZoom = WebSettings.ZoomDensity.FAR
        } else if (mDensity == 160) {
            webSettings.defaultZoom = WebSettings.ZoomDensity.MEDIUM
        } else if (mDensity == 120) {
            webSettings.defaultZoom = WebSettings.ZoomDensity.CLOSE
        } else if (mDensity == DisplayMetrics.DENSITY_XHIGH) {
            webSettings.defaultZoom = WebSettings.ZoomDensity.FAR
        } else if (mDensity == DisplayMetrics.DENSITY_TV) {
            webSettings.defaultZoom = WebSettings.ZoomDensity.FAR
        } else {
            webSettings.defaultZoom = WebSettings.ZoomDensity.MEDIUM
        }
        /**
         * 用WebView显示图片，可使用这个参数 设置网页布局类型： 1、LayoutAlgorithm.NARROW_COLUMNS ：
         * 适应内容大小 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
         */
        webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS


    }

    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     */
    fun getNewContent(htmltext: String?): String? {
        return try {
            val doc = Jsoup.parse(htmltext)
            val elements: Elements = doc.getElementsByTag("img")
            for (element in elements) {
                element.attr("width", "100%")
            }
            doc.toString()
        } catch (e: Exception) {
            htmltext
        }
    }

    fun Setquery() {
        queryInfoPresenter?.netWorkRequestPost(Req_addGoodsStore,
            HttpRequest.waitChange("goods_id", id),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    if (store) {
                        shoucang_iv.setImageResource(R.drawable.ic_shoucang)
                        showToast("取消收藏")
                        store = false

                    } else {
                        shoucang_iv.setImageResource(R.drawable.ic_shoucang1)
                        showToast("收藏成功")
                        store = true

                    }
                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }


            })
    }

}